//
//  LYYPlayListViewController.m
//  Icar
//
//  Created by dllo on 15/10/24.
//  Copyright © 2015年 小龙侠. All rights reserved.
//

#import "LYYPlayListViewController.h"
#import "LYYPlayBarView.h"
#import "LYYListModel.h"
#import "LYYListTableViewCell.h"
#import <AVFoundation/AVFoundation.h>
@interface LYYPlayListViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic,retain)LYYPlayBarView *playView;
@property (nonatomic,retain)UIView *titleView;
@property (nonatomic,retain)UITableView *tableViewo;
@property (nonatomic,retain)NSMutableArray *dataArray;//接收解析数据数组
@property (nonatomic,assign)NSInteger page;
@property (nonatomic,assign)BOOL isUp;
@property (nonatomic,retain)UIButton *sortButton;
@property (nonatomic,retain)LYYListModel *listModel;
//播放
@property (nonatomic,retain)AVPlayerItem *item;
@property (nonatomic,retain)AVPlayer *avPlayer;
@property (nonatomic,assign)NSInteger rowCount;

@end

@implementation LYYPlayListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.dataArray = [[NSMutableArray alloc]init];
    [self setUpPlay];
    [self setUpTableView];
    [self getHeaderRefresh];
    [self getFooterRefresh];
}

- (void)viewWillDisappear:(BOOL)animated{
    [_avPlayer pause];
}

#pragma mark - 数据解析
- (void)getHeaderRefresh{
   __block LYYPlayListViewController *view = self;
    [self.tableViewo addLegendHeaderWithRefreshingBlock:^{
        view.page = 1;
        [view getDataSource:1];
        _isUp = YES;
    }];
    [self.tableViewo.header beginRefreshing];
}

- (void)getFooterRefresh{
    __block LYYPlayListViewController *view = self;
    [self.tableViewo addLegendFooterWithRefreshingBlock:^{
        view.page = view.page + 1;
        [view getDataSource:view.page];
        _isUp = NO;
    }];
    
}

- (void)getDataSource:(NSInteger)number{
    NSString *url = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov5.0.0/News/newsonewradiolist-pm2-aid%ld-p%ld-s50-tp0.json",self.model.album_id,number];
    NSLog(@"id = %ld",self.model.album_id);
    if (ISCONENNCTED == YES) {
        [AFNBlock getDataWithString:url block:^(id back) {
            if (_isUp == YES) {
                [self.dataArray removeAllObjects];
            }
            for (NSDictionary *dic in [[back objectForKey:@"result"]objectForKey:@"list"]) {
                LYYListModel *model = [LYYListModel modelWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            [self.tableViewo.header endRefreshing];
            [self.tableViewo.footer endRefreshing];
            [self.tableViewo reloadData];
        }];
    }
}

#pragma mark - 列表tableview
- (void)setUpTableView{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0,0, WIDTH(375), HEIGHT(214))];
    [self.tableViewo addSubview:headerView];

    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH(375), HEIGHT(184))];
    [backView setBackgroundColor:BLUECOLOR];
    [headerView addSubview:backView];

    UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH(10), HEIGHT(94), WIDTH(80), HEIGHT(80))];
    imgview.layer.cornerRadius = WIDTH(40);
    imgview.layer.borderWidth = .5;
    imgview.layer.masksToBounds = YES;
    imgview.layer.borderColor = [UIColor whiteColor].CGColor;
    [headerView addSubview:imgview];
    [imgview sd_setImageWithURL:[NSURL URLWithString:self.model.album_imgurl] placeholderImage:PLACEHOLDER];
    
    UILabel *albumTitle = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH(90), HEIGHT(94), WIDTH(100), HEIGHT(20))];
    [albumTitle setText:self.model.album_name];
    [headerView addSubview:albumTitle];
    [albumTitle setTextColor:[UIColor whiteColor]];
    
    UILabel *desc = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH(90), HEIGHT(124), WIDTH(280), HEIGHT(50))];
    [desc setText:self.model.album_descrition];
    [desc setTextColor:[UIColor whiteColor]];
    desc.numberOfLines = 3;
    [headerView addSubview:desc];
    
    if (VIEW_HEIGHT == 736) {
        [albumTitle setFont:[UIFont systemFontOfSize:16.]];
        [desc setFont:[UIFont systemFontOfSize:14.]];
    }else if (VIEW_HEIGHT == 667){
        [albumTitle setFont:[UIFont systemFontOfSize:14.]];
        [desc setFont:[UIFont systemFontOfSize:12.]];
    }else if (VIEW_HEIGHT == 568){
        [albumTitle setFont:[UIFont systemFontOfSize:12.]];
        [desc setFont:[UIFont systemFontOfSize:10.]];
    }else{
        [albumTitle setFont:[UIFont systemFontOfSize:10.]];
        [desc setFont:[UIFont systemFontOfSize:8.]];
    }
    
    UIView *buttonView = [[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT(184), WIDTH(375), HEIGHT(30))];
    [buttonView setBackgroundColor:[UIColor colorWithRed:0.904 green:0.966 blue:0.970 alpha:1.000]];
    [headerView addSubview:buttonView];
    
    NSArray *array = @[@"按时间",@"按热度"];
    for (int i = 0; i < 2; i++) {
        _sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sortButton setFrame:CGRectMake(WIDTH(10) + i * WIDTH(60), HEIGHT(0), WIDTH(60), HEIGHT(30))];
        [_sortButton addTarget:self action:@selector(sortButtonClick:) forControlEvents:UIControlEventTouchUpInside];
       
        [_sortButton setTitleColor:BLUECOLOR forState:UIControlStateNormal];
        [_sortButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        [_sortButton setTag:i];
        [_sortButton setTitle:array[i] forState:UIControlStateNormal];
        [buttonView addSubview:_sortButton];
    }
    self.tableViewo = [[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH(375), HEIGHT(603)) style:UITableViewStylePlain];
    self.tableViewo.delegate = self;
    self.tableViewo.dataSource = self;
    [self.tableViewo setBackgroundColor:[LYYNightModeHandle shareNightModeHandle].nightModeColor];
    [self.view addSubview:self.tableViewo];
    self.tableViewo.tableHeaderView = headerView;
    self.tableViewo.showsVerticalScrollIndicator = NO;
    
    
    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH(375), HEIGHT(64))];
    [self.view addSubview:self.titleView];
    [self.titleView setBackgroundColor:[UIColor clearColor]];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH(150), HEIGHT(25), WIDTH(80), HEIGHT(30))];
    [titleLabel setText:@"汽车电台"];
    [self.titleView addSubview:titleLabel];
    titleLabel.textColor = [UIColor whiteColor];
    if (VIEW_HEIGHT == 736) {
        [titleLabel setFont:[UIFont systemFontOfSize:22.]];
    }else if (VIEW_HEIGHT == 667){
        [titleLabel setFont:[UIFont systemFontOfSize:20.]];
    }else if (VIEW_HEIGHT == 568){
        [titleLabel setFont:[UIFont systemFontOfSize:18.]];
    }else{
        [titleLabel setFont:[UIFont systemFontOfSize:16.]];
    }
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(WIDTH(5), HEIGHT(25), WIDTH(30), HEIGHT(30))];
    [self.titleView addSubview:backButton];
    [backButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cee = @"cell";
    LYYListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cee];
    if (!cell) {
        cell = [[LYYListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cee];
        cell.backgroundColor = [LYYNightModeHandle shareNightModeHandle].nightModeColor;
    }
    LYYListModel *model = [self.dataArray objectAtIndex:indexPath.row];
    [cell getModel:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (void)backToView{
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.tabBarController.tabBar.hidden = NO;
}
#pragma mark - 排序
- (void)sortButtonClick:(UIButton *)sender{
    
    if (sender != _sortButton) {
        [_sortButton setTitleColor:BLUECOLOR forState:UIControlStateNormal];
        _sortButton.selected = NO;
        _sortButton = sender;
    }
    [_sortButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    sender.selected = !sender.selected;
    if (sender.tag == 0) {
        [self.dataArray sortUsingSelector:@selector(compareTime:)];
        [self.tableViewo reloadData];
    }else {
        [self.dataArray sortUsingSelector:@selector(compareHot:)];
        [self.tableViewo reloadData];
    }
    
}

#pragma mark - 底部播放条
- (void)setUpPlay{
    self.playView = [[LYYPlayBarView alloc]initWithFrame:CGRectMake(0, HEIGHT(603), WIDTH(375), HEIGHT(64))];
    [self.view addSubview:self.playView];
    [self.playView.lastButton addTarget:self action:@selector(lastButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.playView.nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.playView.playButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - tableview点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _rowCount = indexPath.row;
    self.listModel = [self.dataArray objectAtIndex:indexPath.row];
    [self.playView getModel:self.model listModel:self.listModel];
    [self.playView.playButton setSelected:YES];
    //后台播放
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    self.item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.listModel.program_fileurl]];
    _avPlayer = [AVPlayer playerWithPlayerItem:self.item];
    [_avPlayer play];
    
}

- (void)lastButtonClick{
    if (_rowCount == 0){
        _rowCount = self.dataArray.count - 1;
    }
    if (self.dataArray.count == 1) {
        _rowCount = 0;
    }else{
       _rowCount -= 1;
    }
    self.listModel = [self.dataArray objectAtIndexedSubscript:_rowCount];
    self.item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.listModel.program_fileurl]];
    [_avPlayer replaceCurrentItemWithPlayerItem:self.item];
    [self.playView getModel:self.model listModel:self.listModel];
    self.playView.playButton.selected = YES;
    [_avPlayer play];
}

- (void)nextButtonClick{
     if (_rowCount == self.dataArray.count -  1){
         _rowCount = 0;
    }
    if (self.dataArray.count == 1) {
        _rowCount = 0;
    }else{
        _rowCount += 1;
    }
    self.listModel = [self.dataArray objectAtIndex:_rowCount];
    self.item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.listModel.program_fileurl]];
    [_avPlayer replaceCurrentItemWithPlayerItem:self.item];
    [self.playView getModel:self.model listModel:self.listModel];
    self.playView.playButton.selected = YES;
    [_avPlayer play];
}

- (void)playButtonClick:(UIButton *)sender{
    if (self.item == nil) {
        [sender setImage:[UIImage imageNamed:@"iconfont-iconfont32"] forState:UIControlStateSelected];
    }else{
        sender.selected = !sender.selected;
        if (sender.selected) {
            [_avPlayer play];
        }else{
            [_avPlayer pause];
        }
    }

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.tableViewo.contentOffset.y > 30 && self.tableViewo.contentOffset.y < 64) {
        self.titleView.alpha = self.tableViewo.contentOffset.y / 34;
        [self.titleView setBackgroundColor:BLUECOLOR];
    }else if (self.tableViewo.contentOffset.y > 64){
        [self.titleView setBackgroundColor:BLUECOLOR];
        self.titleView.alpha = 1;
    }else if (self.tableViewo.contentOffset.y == 0){
        [self.titleView setBackgroundColor:[UIColor clearColor]];
    }
    [self.tableViewo reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {/Users/dllo/Downloads/iconfont-headphones.png
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
